<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>账户管理</title>
	<link rel="stylesheet" href="../../component/pear/css/pear.css" />
</head>

<body class="pear-container">
	<div class="layui-card">
		<div class="layui-card-body">
			<form class="layui-form" action="">
				<div class="layui-form-item">
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">用户名</label>
						<div class="layui-input-inline">
							<input type="text" name="username" id="username" placeholder="" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">手机号码</label>
						<div class="layui-input-inline">
							<input type="text" name="mobile" id="mobile" placeholder="" class="layui-input">
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">账号状态</label>
						<div class="layui-input-inline">
							<select name="status" id="status" lay-search>
								<option value="">请下拉选择</option>
								<option value="0">禁用</option>
								<option value="1">启用</option>
							</select>
						</div>
					</div>
					<div class="layui-form-item layui-inline">
						<label class="layui-form-label">账户类型</label>
						<div class="layui-input-inline">
							<select name="is_admin" id="is_admin" lay-search>
								<option value="">请下拉选择</option>
								<option value="0">管理员</option>
								<option value="1">普通用户</option>
							</select>
						</div>
					</div>
					<br>
					<div class="layui-form-item layui-inline">
						<button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="base-query">
							<i class="layui-icon layui-icon-search"></i>
							查询
						</button>
						<button type="reset" class="pear-btn pear-btn-md">
							<i class="layui-icon layui-icon-refresh"></i>
							重置
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>
	<div class="layui-card">
		<div class="layui-card-body">
			<table id="base-table" lay-filter="base-table"></table>
		</div>
	</div>

	<script type="text/html" id="base-toolbar">
			<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
		        <i class="layui-icon layui-icon-add-1"></i>
		        新增
		    </button>
		    <!-- <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
		        <i class="layui-icon layui-icon-delete"></i>
		        删除
		    </button> -->
		</script>

	<script type="text/html" id="base-bar">
			<button class="pear-btn pear-btn-md pear-btn-sm" lay-event="update_pwd"><i class="layui-icon layui-icon-add-1"></i>密码</button>
			<button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</button>
		    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i class="layui-icon layui-icon-delete"></i>删除</button>
		</script>


	<script type="text/html" id="base-createTime">
			{{layui.util.toDateString(d.create_time, 'yyyy-MM-dd HH:mm:ss')}}
		</script>
	<script type="text/html" id="base-updateTime">
			{{layui.util.toDateString(d.update_time, 'yyyy-MM-dd HH:mm:ss')}}
		</script>

	<script type="text/html" id="base-status">
			{{#if (d.status == 0) { }}
			<i class="layui-icon layui-icon-face-cry" style="font-size: 30px; color: #ff1e1e;"><span>禁用</span></i>  
			 <!-- <i class="layui-icon"><span>禁用</span></i>   -->
		    {{# }else if(d.status == 1){ }}
			<i class="layui-icon layui-icon-face-smile" style="font-size: 30px; color: #1E9FFF;"><span>启用</span></i> 
			 <!-- <i class="layui-icon"><span>启用</span></i>  -->
		    {{# } }}
	</script>
	<script type="text/html" id="base-is-admin">
			{{#if (d.is_admin == 0) { }}
			<!-- <i class="layui-icon layui-icon-face-cry" style="font-size: 30px; color: #ff1e1e;"><span>管理员</span></i>   -->
			 <i class="layui-icon"><span>管理员</span></i>  
		    {{# }else if(d.is_admin == 1){ }}
			<!-- <i class="layui-icon layui-icon-face-smile" style="font-size: 30px; color: #1E9FFF;"><span>普通用户</span></i>  -->
			 <i class="layui-icon"><span>普通用户</span></i> 
		    {{# } }}
		</script>

	<script src="../../component/com/api.js"></script>
	<script src="../../component/com/auth.js"></script>
	<script src="../../component/layui/layui.js"></script>
	<script src="../../component/pear/pear.js"></script>
	<script>
		layui.use(['table', 'form', 'jquery', 'common'], function () {
			let table = layui.table;
			let form = layui.form;
			let $ = layui.jquery;
			let common = layui.common;
			let laydate = layui.laydate;
			let MODULE_PATH = "config/";
			let API_BASE_URL = apiConfig.baseUrl;
			let token = window.localStorage.getItem("token") || window.sessionStorage.getItem("token")

			let cols = [
				[{
					type: 'checkbox'
				},
				{
					title: '序号',
					field: 'id',
					align: 'left',
					width: 80,
				},
				{
					title: '用户名',
					field: 'username',
					align: 'left',
					width: 100,
				},
				{
					title: '手机号',
					field: 'mobile',
					align: 'center',
					width: 150,
				},
				{
					title: "账号状态",
					field: 'status',
					align: 'center',
					width: 100,
					templet: '#base-status'
				},
				{
					title: "账户类型",
					field: 'is_admin',
					align: 'center',
					templet: '#base-is-admin',
					width: 100,
				},
				{
					title: '最后登录时间',
					field: 'last_login_time',
					align: 'center',
					width: 160,
					templet: '#base-createTime',
				},
				{
					title: '创建时间',
					field: 'create_time',
					align: 'center',
					width: 160,
					templet: '#base-createTime',
				},
				{
					title: '更新时间',
					field: 'update_time',
					align: 'center',
					width: 160,
					templet: '#base-updateTime',
					hide: true
				},
				{
					title: '操作',
					toolbar: '#base-bar',
					align: 'center',
					width: 230,
					fixed: "right"
				}
				]
			]

			table.render({
				elem: '#base-table',
				url: `${API_BASE_URL}/common/account/`, // 后端接口地址
				page: true, // 启用分页
				// 1. 关键：配置分页请求参数（与后端接收的参数名匹配）
				request: {
					pageName: 'page', // 后端接收的“当前页”参数名（你的后端用page，如?page=1）
					limitName: 'limit' // 后端接收的“每页条数”参数名（你的后端用limit，如?limit=10）
				},
				// 2. 关键：配置分页控件显示（可选，优化用户体验）
				limits: [10, 20, 30, 40, 50, 100], // 每页条数选择器
				limit: 10, // 默认每页10条（需与后端默认page_size一致）
				cols: cols, // 表格列定义（不变）
				skin: 'line',
				toolbar: '#base-toolbar',
				// 3. 关键：请求头携带token（不变，但确保正确）
				headers: {
					"Authorization": token
				},
				// 4. 核心：解析后端返回数据，映射为Layui表格需要的格式
				parseData: function (res) {
					// res是后端返回的完整数据：{success: true, code:200, message:"", data:{count:4, current_page:1, ...}}
					return {
						"code": res.success ? 0 : 1, // Layui要求：成功返回0，失败返回非0
						"msg": res.message || "操作成功", // 提示信息
						"count": res.data.count, // 总数据量（关键：分页控件依赖此值计算总页数）
						"data": res.data.results, // 表格数据列表（后端放在data.results中）
						// 5. 关键：同步当前页状态（让分页控件显示正确的“当前页”）
						"curr": res.data.current_page // 从后端返回的data.current_page获取当前页
					};
				},
				// 6. 可选：默认工具栏（不变）
				defaultToolbar: [{
					title: '刷新',
					layEvent: 'refresh',
					icon: 'layui-icon-refresh',
				}, 'filter', 'print', 'exports']
			});


			table.on('tool(base-table)', function (obj) {
				switch (obj.event) {
					case "update_pwd":
						window.update_pwd(obj)
						break;
					case "edit":
						window.edit(obj)  
						break;
					case "remove":
						window.remove(obj)
						break;
				}
			});

			table.on('toolbar(base-table)', function (obj) {
				switch (obj.event) {
					case "add":
						window.add(obj)
						break;
					case "refresh":
						window.refresh(obj)
						break;
					case "batchRemove":
						window.batchRemove(obj)
						break;
				}
			});

			form.on('submit(base-query)', function (data) {
				table.reload('base-table', {
					where: data.field
				})
				return false;
			});

			window.add = function () {
				layer.open({
					type: 2,
					title: '新增账号',
					shade: 0.1,
					area: ['600px', '450px'],
					// area: [common.isModile() ? '100%' : '600px', common.isModile() ? '100%' : '800px'],
					content: MODULE_PATH + 'account-add.html'
				});
			}

			window.update_pwd = function (obj) {
				layer.open({
					type: 2,
					title: '更新密码',
					shade: 0.1,
					area: [common.isModile() ? '100%' : '400px', common.isModile() ? '100%' : '250px'],
					content: MODULE_PATH + `account-update-pwd.html?id=${obj.data.id}`
				});
			}

			window.edit = function (obj) {
				layer.open({
					type: 2,
					title: `编辑账号: [${obj.data.username}]`,
					shade: 0.1,
					area: ['600px', '450px'],
					content: MODULE_PATH + `account-edit.html?id=${obj.data.id}`
				});
			}

			window.remove = function (obj) {
				layer.confirm(`确定要删除用户：[ ${obj.data.username} ] ？`, {
					icon: 3,
					title: '提示: 账号删除'
				}, function (index) {
					layer.close(index);
					let loading = layer.load();
					$.ajax({
						url: `${API_BASE_URL}/common/account/${obj.data.id}/`,
						dataType: 'json',
						type: 'delete',
						headers: {
							"Authorization": token
						},
						success: function (result) {
							layer.close(loading);
							if (result.success) {
								layer.msg(result.message, {
									icon: 1,
									time: 1000
								}, function () {
									obj.del();
								});
							} else {
								layer.msg(result.message, {
									icon: 2,
									time: 1000
								});
							}
						}
					})
				});
			}

			window.refresh = function (param) {
				table.reload('base-table');
			}
		})
	</script>
</body>

</html>